package com.hyperfix.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyperfix.common.exception.CustomException;
import com.hyperfix.common.holder.UserHolder;
import com.hyperfix.common.service.MailService;
import com.hyperfix.models.common.R;
import com.hyperfix.models.user.dtos.UserDTO;
import com.hyperfix.models.user.vos.LoginVO;
import com.hyperfix.models.user.pojos.User;
import com.hyperfix.models.user.vos.PasswordFindVO;
import com.hyperfix.models.user.vos.PasswordUpdateVO;
import com.hyperfix.user.mapper.UserMapper;
import com.hyperfix.user.service.UserService;
import com.hyperfix.utils.common.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hyperfix.models.constant.common.LoginConstant.*;
import static com.hyperfix.models.constant.common.RandomPasswordConstant.ORIGIN_PASSWORD;

/**
 * @author JiangChunYu
 * 2024/4/5
 */
@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MailService mailService;

    @Override
    public R<UserDTO> login(LoginVO loginVO) {
        // 校验验证码
        String captchaId = CAPTCHA_KEY_PREFIX + loginVO.getCaptchaToken();
        String captcha = stringRedisTemplate.opsForValue().get(captchaId);
        if (!loginVO.getCode().equalsIgnoreCase(captcha)) {
            return R.error("验证码错误");
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, loginVO.getUsername()));
        // 校验账号密码
        if (user == null) {
            return R.error("用户不存在");
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(loginVO.getPassword().getBytes());
        if (!encryptedPassword.equals(user.getPassword())) {
            return R.error("密码错误");
        }
        // 检查账号是否被禁用
        Integer status = user.getStatus();
        if (status != null && status == 0) {
            return R.error("账号已被禁用，请联系管理员");
        }
        // 修改上一次登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateById(user);
        // 签发jwt
        String jwt = JwtUtil.createJWT(user.getUsername());
        // 将token和必要用户信息存入redis
        stringRedisTemplate.opsForValue().set(LOGIN_KEY_PREFIX + user.getUsername(), jwt, LOGIN_TTL_DAY, TimeUnit.DAYS);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        stringRedisTemplate.opsForValue().set(LOGIN_USER_PREFIX + user.getUsername(), JSON.toJSONString(userDTO), LOGIN_TTL_DAY, TimeUnit.DAYS);
        // 删除redis中验证码
        stringRedisTemplate.delete(captchaId);
        return R.success(userDTO).add("token", jwt);
    }

    @Override
    public R<String> disable(String username) {
        // 检查管理员是否禁用/启用自己
        UserDTO userDTO = UserHolder.getUser();
        String currentUsername = userDTO.getUsername();
        if (username.equals(currentUsername)) {
            return R.error("不能自我禁用");
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user == null) {
            return R.error("切换用户状态失败，用户不存在");
        }
        Integer status = user.getStatus();
        if (status == null) {
            throw new CustomException("系统错误，用户状态不存在");
        }
        int newStatus = status ^ 1;
        user.setStatus(newStatus);
        userMapper.updateById(user);
        return R.success("用户状态切换成功");
    }

    @Override
    public R<String> changePassword(PasswordUpdateVO passwordUpdateVO, String token) {
        UserDTO userDTO = UserHolder.getUser();
        String username = userDTO.getUsername();
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        // 校验账号密码
        if (user == null) {
            throw new CustomException("用户不存在");
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(passwordUpdateVO.getOldPassword().getBytes());
        if (!encryptedPassword.equals(user.getPassword())) {
            return R.error("密码错误");
        }
        String encryptedNewPassword = DigestUtils.md5DigestAsHex(passwordUpdateVO.getNewPassword().getBytes());
        user.setPassword(encryptedNewPassword);
        userMapper.updateById(user);
        boolean success = clearUserContext(token, username);
        if (!success) {
            throw new CustomException("系统出错，修改密码失败");
        }
        return R.success("修改密码成功，请重新登录");
    }

    @Override
    public boolean clearUserContext(String token, String username) {
        List<String> list = new ArrayList<>();
        list.add(LOGIN_KEY_PREFIX + username);
        list.add(LOGIN_USER_PREFIX + username);
        Long deleteNum = stringRedisTemplate.delete(list);
        if (deleteNum == null || deleteNum != 2) {
            throw new CustomException("系统错误，清楚用户上下文失败");
        }
        return true;
    }

    @Override
    public R<String> findPassword(PasswordFindVO passwordFindVO) {
        // 校验绑定邮箱
        String username = passwordFindVO.getUsername();
        String userEmail = userMapper.selectUserEmail(username);
        if (!passwordFindVO.getEmail().equals(userEmail)) {
            return R.error("找回密码失败，邮箱错误");
        }
        // 重设密码
        String newPassword = RandomUtil.randomString(ORIGIN_PASSWORD, 10);
        String encryptedPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        boolean resetSuccess = userMapper.resetPassword(username, encryptedPassword);
        if (!resetSuccess) {
            throw new CustomException("系统出错，找回密码失败");
        }
        // 发邮件告知用户新密码
        Map<String, Object> values = new HashMap<>();
        values.put("username", username);
        values.put("password", newPassword);
        mailService.sendEmailToUser(userEmail, "findPassword", values);
        return R.success("找回密码成功，请重新登录");
    }
}
